#include "viml/compiler.h"
#include "viml/instruction.h"
#include <gtest/gtest.h>

namespace viml {

class BasicCompilerTest : public ::testing::Test {
protected:
    Compiler compiler_;
};

TEST_F(BasicCompilerTest, NumberLiteral) {
    // 测试数字字面量编译
    auto result = compiler_.compile("42");
    
    // 验证编译成功
    EXPECT_TRUE(result.success);
    EXPECT_TRUE(result.errors.empty());
    EXPECT_NE(result.function, nullptr);
    
    // 验证生成的字节码
    const auto& bytecode = result.function->bytecode;
    ASSERT_FALSE(bytecode.empty());
    
    // 应该生成LOAD_CONST指令
    EXPECT_EQ(bytecode[0].opcode, OpCode::LOAD_CONST);
}

TEST_F(BasicCompilerTest, StringLiteral) {
    // 测试字符串字面量编译
    auto result = compiler_.compile("\"hello\"");
    
    // 验证编译成功
    EXPECT_TRUE(result.success);
    EXPECT_TRUE(result.errors.empty());
    EXPECT_NE(result.function, nullptr);
    
    // 验证生成的字节码
    const auto& bytecode = result.function->bytecode;
    ASSERT_FALSE(bytecode.empty());
    
    // 应该生成LOAD_CONST指令
    EXPECT_EQ(bytecode[0].opcode, OpCode::LOAD_CONST);
}

TEST_F(BasicCompilerTest, BooleanLiteral) {
    // 测试布尔字面量编译
    auto result = compiler_.compile("true");
    
    // 验证编译成功
    EXPECT_TRUE(result.success);
    EXPECT_TRUE(result.errors.empty());
    EXPECT_NE(result.function, nullptr);
    
    // 验证生成的字节码
    const auto& bytecode = result.function->bytecode;
    ASSERT_FALSE(bytecode.empty());
    
    // 应该生成LOAD_TRUE指令
    EXPECT_EQ(bytecode[0].opcode, OpCode::LOAD_TRUE);
}

TEST_F(BasicCompilerTest, NilLiteral) {
    // 测试nil字面量编译
    auto result = compiler_.compile("nil");
    
    // 验证编译成功
    EXPECT_TRUE(result.success);
    EXPECT_TRUE(result.errors.empty());
    EXPECT_NE(result.function, nullptr);
    
    // 验证生成的字节码
    const auto& bytecode = result.function->bytecode;
    ASSERT_FALSE(bytecode.empty());
    
    // 应该生成LOAD_NIL指令
    EXPECT_EQ(bytecode[0].opcode, OpCode::LOAD_NIL);
}

TEST_F(BasicCompilerTest, SimpleArithmetic) {
    // 测试简单算术表达式编译
    auto result = compiler_.compile("1 + 2");
    
    // 验证编译成功
    EXPECT_TRUE(result.success);
    EXPECT_TRUE(result.errors.empty());
    EXPECT_NE(result.function, nullptr);
    
    // 验证生成的字节码
    const auto& bytecode = result.function->bytecode;
    ASSERT_GE(bytecode.size(), 3); // 至少3条指令: 2个LOAD_CONST + 1个ADD
    
    // 验证指令序列
    EXPECT_EQ(bytecode[0].opcode, OpCode::LOAD_CONST);
    EXPECT_EQ(bytecode[1].opcode, OpCode::LOAD_CONST);
    EXPECT_EQ(bytecode[2].opcode, OpCode::ADD);
}

} // namespace viml